//
//  RSAUtility.swift
//  KCSwift
//
//  Created by apple on 2023/7/31.
//

import Foundation
import Security

class RSAUtility {
    
    static func encryptString(_ string: String, publicKey: SecKey) -> Data? {
        guard let stringData = string.data(using: .utf8) else {
            return nil
        }
        
        let blockSize = SecKeyGetBlockSize(publicKey)
        var encryptedData = [UInt8](repeating: 0, count: blockSize)
        var encryptedDataLength = blockSize
        
        stringData.withUnsafeBytes { stringBytes in
            let status = SecKeyEncrypt(publicKey, .PKCS1, stringBytes.baseAddress!.assumingMemoryBound(to: UInt8.self), stringData.count, &encryptedData, &encryptedDataLength)
            
            guard status == errSecSuccess else {
                return
            }
        }
        
        return Data(bytes: encryptedData, count: encryptedDataLength)
    }
    
    static func decryptData(_ data: Data, privateKey: SecKey) -> String? {
        let blockSize = SecKeyGetBlockSize(privateKey)
        var decryptedDataBuffer = [UInt8](repeating: 0, count: blockSize)
        var decryptedDataLength = blockSize
        
        data.withUnsafeBytes { dataBytes in
            let status = SecKeyDecrypt(privateKey, .PKCS1, dataBytes.baseAddress!.assumingMemoryBound(to: UInt8.self), data.count, &decryptedDataBuffer, &decryptedDataLength)
            
            guard status == errSecSuccess else {
                return
            }
        }
        
        let decryptedData = Data(bytes: decryptedDataBuffer, count: decryptedDataLength)
        return String(data: decryptedData, encoding: .utf8)
    }
    
}
